package basic.JUC.print100;

import basic.JUC.FirstTrial;

/**
 * @创建人 MBY381
 * @创建时间 2022/4/13 15:07
 * @描述 暂无
 */
public class CASprintSWAP {
    volatile static int i = 0;// 初始值为0
    volatile static int tag = 0;// 初始值为0
    volatile static int value=0;

    public static void main(String[] args) throws InterruptedException {
        print();

    }

    public static void print() throws InterruptedException {
        Thread thread1=new Thread(() -> {
            for (int i = 1; i < 100; i = i + 2) {
                while (tag != 0) {
                }
                FirstTrial.printThreadName();
                System.out.println(i);
                System.out.println(value++);
                tag = 1;

            }
        });
        Thread thread2=new Thread(() -> {
            for (int i = 2; i <= 100; i = i + 2) {
                while (tag != 1) {
                }

                FirstTrial.printThreadName();
                System.out.println(i);
                System.out.println(value++);
                tag = 0;

            }
        });
        thread2.start();
        thread1.start();
//        thread1.join();
//        thread2.join();
        System.out.println("mbyzzqzqzqqzqzq");

    }

    public static void CASprint() {
        char[] charArray1 = "123456789".toCharArray();
        char[] charArray2 = "ABCDEFGHI".toCharArray();


        new Thread(() -> {
            for (char c : charArray2) {
                // 自旋锁原理
                // 当i不等于0时一直自旋，只有检测到i不为0时执行打印输出一个字符
                while (i != 0) {
                }
                FirstTrial.printThreadName();
                System.out.println(c);
                // 打印完以后变更i
                i = 1;
            }
        }, "thread1").start();

        new Thread(() -> {
            for (char c : charArray1) {
                while (i != 1) {
                }
                FirstTrial.printThreadName();
                System.out.println(c);
                i = 0;
            }
        }, "thread2").start();
    }

}
